package com.example.aspect;

import com.example.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

@Aspect
@Component
@Slf4j
public class UpdateAspect {
    @Around("@annotation(com.example.log.UpdateLog)")
    public Result updateAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("执行updateLog增强");
        Object obj = joinPoint.getArgs()[0];
        if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            for (Object item : list) {
                initParameter(item);
            }
        } else {
            initParameter(obj);
        }
        Object proceed = joinPoint.proceed();
        return (Result) proceed;
    }

    private void initParameter (Object item) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Class<?> clazz = item.getClass();
        Method setUpdateTime = clazz.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
        setUpdateTime.setAccessible(true);
        setUpdateTime.invoke(item, LocalDateTime.now());
    }

}
